﻿using Game.Model;
using UnityEngine;

namespace Game.UiState
{
    /// <summary>
    /// 游戏 Ui 状态
    /// </summary>
    public class GameState : Manager.IUiState
    {
        private Transform _World;
        private Transform _TemplateRoot;
        
        public void OnEnter()
        {
            var manager = Manager.Instance;
            var gameView = manager.GameView;
            gameView.SetActive(true);
            _World = gameView.transform.Find("World");
            _TemplateRoot = gameView.transform.Find("Template");
            _TemplateRoot.gameObject.SetActive(false);
        }

        public void OnUpdate()
        {
            var modelManager = ModelManager.Instance;
            if (modelManager.IsNeedRefresh)
            {
                for (var i = 0; i < _World.childCount; i++)
                {
                    Object.Destroy(_World.GetChild(i).gameObject);
                }

                {
                    GameObject mapCharacterTemplate = null;
                    var objects = modelManager.GetMapObjects();
                    foreach (var mapObject in objects)
                    {
                        if (mapObject is MapCharacter mapCharacter)
                        {
                            if (mapCharacterTemplate == null)
                            {
                                mapCharacterTemplate = _TemplateRoot.Find("MapCharacterView").gameObject;
                            }

                            var view = Object.Instantiate(mapCharacterTemplate, _World).GetComponent<MapCharacterView>();
                            view.gameObject.SetActive(true);
                            view.SetMapCharacter(mapCharacter);
                        }
                    }
                }
                
                modelManager.CompleteRefresh();
            }
        }

        public void OnExit()
        {
            var manager = Manager.Instance;
            manager.GameView.SetActive(false);
        }
    }
}